package com.example.lianguisystem.utils.licensePlate;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.example.lianguisystem.config.PostConstructUtil;
import com.google.common.net.MediaType;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@UtilityClass
public class CommonUtil {
    final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     *
     * @param url 文件下载地址
     * @param filePath 文件存放路径
     * @param fileName 文件名
     * @return file 文件路径+文件名
     */
    public static String FRDownload(String url,String filePath,String fileName){

        String file = filePath+fileName;//文件全路径，包含文件名

        FileOutputStream fileOut = null;
        HttpURLConnection conn = null;
        InputStream inputStream = null;
        try
        {
            // 建立链接
            URL httpUrl=new URL(url);
            conn=(HttpURLConnection) httpUrl.openConnection();
            //以Post方式提交表单，默认get方式
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            // post方式不能使用缓存
            conn.setUseCaches(false);
            //连接指定的资源
            conn.connect();
            //获取网络输入流
            inputStream=conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            //判断文件的保存路径后面是否以/结尾
            if (!filePath.endsWith("/")) {
                filePath += "/";
            }
            //写入到文件（注意文件保存路径的后面一定要加上文件的名称）
            fileOut = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fileOut);

            byte[] buf = new byte[4096];
            int length = bis.read(buf);
            //保存文件
            while(length != -1)
            {
                bos.write(buf, 0, length);
                length = bis.read(buf);
            }
            bos.close();
            bis.close();
            conn.disconnect();
        } catch (Exception e)
        {
            e.printStackTrace();
            System.out.println("抛出异常！！");
        }
        return file;
    }

    /**
     * 是否是本地
     * @return
     */
    public static Boolean isLocalhost() {
        InetAddress localHost = null;
        try {
            localHost = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        String hostName = localHost.getHostName();
        if ("DC22121901".equals(hostName)) {
            return true;
        }
        return false;
    }


    public static void moveFile(String savePath, File file) {
        FileInputStream is = null;
        FileOutputStream os = null;
        try {
            is = new FileInputStream(file);
            File newFile = new File(savePath);
            os = new FileOutputStream(newFile);
            int length = 0;
            byte[] buffer = new byte[1024 * 1024];
            while ((length = is.read(buffer)) != -1) {
                os.write(buffer, 0, length);
            }
        } catch (Exception e) {
        } finally {
            try {
                is.close();
                os.flush();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        file.delete();
    }

    public static boolean isWorkDay() {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM");
        String format = LocalDate.now().format(dtf);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//        Date now = sdf.parse("2023-11-07");
        Date day05 = null;
        try {
            day05 = sdf.parse(format + "-05");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Date now = new Date();
        Calendar instance = Calendar.getInstance();
        instance.setTime(now);
        int dayOfMonth = instance.get(Calendar.DAY_OF_MONTH);
        int interval = dayOfMonth - 5;
        instance.setTime(day05);
        int i = instance.get(Calendar.DAY_OF_WEEK);
        if (interval == 0 && i != 7 && i != 1) {
            return true;
        }
        if (interval == 1 && i == 1) {
            return true;
        }
        if (interval == 2 && i == 7) {
            return true;
        }
        return false;

    }

    public String getBase64OfImage(String filePath) {
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(filePath);
            int available = inputStream.available();
            byte[] bytes = new byte[available];
            inputStream.read(bytes);
            Base64.Encoder encoder = Base64.getEncoder();
            String encode = encoder.encodeToString(bytes);
            return "data:image/jpeg;base64," + encode;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    public String get4UserId(String name) {
        if (StrUtil.isBlank(name)) {
            return "|";
        }
        Map<String, String> userMap = PostConstructUtil.getUserMap();
        String userId = "|";
        String[] split = name.split("[,，；;:：]");
        for (String temp : split) {
            userId += userMap.get(temp) + "|";
        }
        return userId;
    }

    public String getAccessToken() throws IOException {
        String key = "jeecg:license:plate";
        String accessToken = stringRedisTemplate.opsForValue().get(key);
        if (accessToken != null) {
            log.debug("redis-" + accessToken);
            return accessToken;
        }
        MediaType mediaType = MediaType.parse("application/json");
        String clientId = "zTVHwkDOXU68ioGxdXrCANVP";
        String clientSecret = "YH8jmGbNqdbQi0n4eYF5OGGG1SE48gtI";
//        String clientId = "AZBs51CAeVWWHmVFXaN25Fl6";
//        String clientSecret = "5iSIqEBQ3pkMkzdxu2aqEqUtKVGC3UQT";
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token?client_id=" + clientId + "&client_secret=" + clientSecret + "&grant_type=client_credentials")
                .method("GET", null)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();

        Response response = HTTP_CLIENT.newCall(request).execute();
//        System.out.println(response.body().string());
        String body = response.body().string();
        JSONObject jsonObject = JSONObject.parseObject(body);
        accessToken = (String) jsonObject.get("access_token");
        Integer expiresIn = jsonObject.getInteger("expires_in");
        stringRedisTemplate.opsForValue().set(key, accessToken, expiresIn, TimeUnit.SECONDS);
        log.debug("require-" + accessToken);
        return accessToken;
    }
}
